package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/dish/page")
    //1.接受参数
    public ResultInfo findPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                               String name) {
        //2.调用service查询
        Page<Dish> page = dishService.findPage(pageNum, pageSize, name);
        //返回结果
        return ResultInfo.success(page);
    }



    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        //定义菜品缓存的key
        String key="dish_"+dish.getCategoryId();
//删除key通用操作不需要ops
        redisTemplate.delete(key);

        //调用service进行保存
        dishService.save(dish);
        //返回结果
        return ResultInfo.success(null);

    }

    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable Long id) {
        //调用service根据菜品id查询
        Dish byId = dishService.findById(id);
        return ResultInfo.success(byId);
    }

    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {

        //定义菜品缓存的key
        String key="dish_"+dish.getCategoryId();
//删除key通用操作不需要ops
        redisTemplate.delete(key);

        //调用service进行保存
        dishService.update(dish);
        //返回成功消息
        return ResultInfo.success(null);
    }

    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(@RequestParam List<Long> ids) {
        Set keys = redisTemplate.keys("dish_*");

        redisTemplate.delete(keys);
        dishService.deleteById(ids);
        return ResultInfo.success(null);
    }

    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        dishService.updateStatus(status, ids);
        return ResultInfo.success(null);
    }

    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId, String name) {
        if (name != null) {
            List<Dish> dishes = dishService.fingdishByName(name);
            return ResultInfo.success(dishes);
        } else {
            List<Dish> byCategoryId = dishService.findByCategoryId(categoryId);
            return ResultInfo.success(byCategoryId);
        }

    }
}
